package com.frat.controller;

import java.util.ArrayList;

import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;

public class BluetoothListActivity extends ListActivity {

	private final String TAG = this.getClass().getSimpleName();
	
	private BluetoothAdapter bAdapter;
	private BluetoothListAdapter listAdapter;
	private ArrayList<BluetoothDevice> deviceList;
	
	// Create a BroadcastReceiver for ACTION_FOUND
	private final BroadcastReceiver receiver = new BroadcastReceiver() {
	    public void onReceive(Context context, Intent intent) {
	        String action = intent.getAction();
	        // When discovery finds a device
	        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
	            // Get the BluetoothDevice object from the Intent
	            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	            
	            Log.d(TAG, "Device: " + device.getName() + " was found!");
	            
	            deviceList.add(device);
	            listAdapter.notifyDataSetChanged();
	        }
	    }
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bluetoothlist);
		
		bAdapter = BluetoothAdapter.getDefaultAdapter();
		deviceList = new ArrayList<BluetoothDevice>();
		listAdapter= new BluetoothListAdapter(this, R.layout.bluetooth_list_item, deviceList);
		
		setListAdapter(listAdapter);
		
		Log.d(TAG, "Discovery started");
		bAdapter.startDiscovery();
		
		// Register the BroadcastReceiver
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		registerReceiver(receiver, filter); // Don't forget to unregister during onDestroy
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
		Log.d(TAG, "Discovery cancelled");
		bAdapter.cancelDiscovery();
	}
	
}
